#include<iostream>
#include<string>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include"Protocol.hpp"
int main(int argc,char* argv[])
{
    if(argc!=3){
        std::cout<<"Usage: "<<argv[0]<<" <server_ip> <port>"<<std::endl;
        return 1;
    }
    int port=std::stoi(argv[2]);
    std::string ip = argv[1];
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0){
        std::cout<<"create socket error"<<std::endl;
        return 2;
    }
    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
    //建立连接
    int n = ::connect(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
    
    if(n<0){
        std::cout<<"connect error"<<std::endl;
        return 3;
    }
    while(true){
        int x,y;
        char op;
        std::cout<<"Input X"<<std::endl;
        std::cin>>x;
        std::cout<<"Input Y"<<std::endl;
        std::cin>>y;
        std::cout<<"Input Operator"<<std::endl;
        std::cin>>op;
        //发送消息
        std::string send_msg;
        Request request(x,y,op);
        request.Serialize(send_msg);
        Encode(send_msg);
        int n = ::send(sockfd,send_msg.c_str(),send_msg.size(),0);
        if(n<0){
            std::cout<<"send error"<<std::endl;
            break;
        }
        else{
            char buffer[1024];
            int m = ::recv(sockfd,buffer,sizeof(buffer)-1,0);
            if(m>0){
                buffer[m] = 0;
                std::string msg = buffer;
                std::string recv_msg;
                Decode(msg,&recv_msg);//解码报文

                Response response;
                response.Deserialize(recv_msg);//反序列化
                
                std::cout<<response.GetResult()<<"["<<response.GetCode()<<"]"<<std::endl;
            }
            else{
                break;
            }
        }
    }
    ::close(sockfd);

    return 0;
}